<template>
  <div>
    <el-container>
      <el-header style="margin-top: 10px;height: auto;">
        <el-row>
          <el-input
            v-model="kwInput"
            placeholder="输入 任意字符 进行筛选"
            class="input-with-select"
            clearable
            @keyup.native.enter="handleSearch"
          >
            <el-button slot="append" icon="el-icon-search" @click="handleSearch">搜索</el-button>
          </el-input>
          <el-button
            type="primary"
            class="el-icon-plus add-btn"
            :disabled="listLoading"
            @click="handleAction('create', '添加')"
          >添加
          </el-button>
        </el-row>
      </el-header>
      <el-main>
        <el-table
          ref="dragTable"
          v-loading="listLoading"
          :data="data"
          row-key="id"
          border
          fit
          highlight-current-row
          style="width: 100%"
          :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
        >
          <el-table-column align="center" label="Drag" width="80">
            <template slot-scope="{}">
              <svg-icon class="drag-handler" icon-class="drag" />
            </template>
          </el-table-column>
          <el-table-column align="left" label="name" prop="name" sortable="custom" width="300">
            <template slot-scope="scope">
              <span v-if="scope.row.parent_id"><el-tag effect="dark" :size="scope.row.parent_id ? 'mini': 'small'" :color="scope.row.parent__color">{{ scope.row.parent__name }}</el-tag>></span>
              <el-tag effect="dark" :size="scope.row.parent_id ? 'mini': 'small'" :color="scope.row.color">{{ scope.row.name }}</el-tag>
              <el-button v-if="!scope.row.parent_id" plain icon="el-icon-plus" size="mini" style="float: right" title="添加子元素" @click="handleAction('addchildren', scope.row)" />
            </template>
          </el-table-column>
          <el-table-column align="center" label="流程顺序" prop="index" sortable="custom">
            <template slot-scope="scope">
              <el-input v-model="scope.row.index" placeholder="请输入内容">
                <template slot="append">保存</template>
              </el-input>
            </template>
          </el-table-column>
          <el-table-column align="center" label="处理部门" prop="crmdepartment__name" sortable="custom" />
          <el-table-column align="center" label="审批人" prop="manager" sortable="custom" />
          <el-table-column align="center" label="钉钉链接" prop="dingding_hook" sortable="custom">
            <template slot-scope="scope">
              {{ scope.row.dingding_hook ? scope.row.dingding_hook.slice(-6) : '' }}
            </template>
          </el-table-column>
          <el-table-column align="center" label="操作" width="350">
            <template slot-scope="scope">
              <el-button size="mini" type="primary" @click="handleAction('edit', scope.row)">修改</el-button>
              <el-button size="mini" type="success" title="设置SOP任务目标" @click="handleAction('sop', scope.row)">
                <i class="el-icon-s-flag" />SOP
              </el-button>
              <el-button size="mini" type="danger" @click="handleAction('delete', scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination
          v-if="data.length"
          background
          class="mt-pagination"
          :current-page="page"
          :page-sizes="[10,20,50,100]"
          :page-size="pagesize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handlePageChange"
        />
        <el-alert
          title="提示"
          type="warning"
          description="建议使用不同色彩标注操作，审批或者不同部门！如果指定负责人，该状态不再支持抢单！抢单类型必须填写钉钉的群机器人链接，否则收不到通知。"
          :closable="false"
        />
        <!--             <div class="show-d">-->
        <!--                <el-tag>The default order :</el-tag> {{ oldList }}-->
        <!--              </div>-->
        <!--              <div class="show-d">-->
        <!--                <el-tag>The after dragging order :</el-tag> {{ newList }}-->
        <!--              </div>-->
      </el-main>
    </el-container>
    <el-dialog
      append-to-body
      :title="title"
      :width="width"
      :visible.sync="innerDialogVisible"
      :close-on-click-modal="false"
    >
      <el-form :model="temp" label-position="left" label-width="120px">
        <el-form-item label="状态名称">
          <el-input v-model="temp.name" />
        </el-form-item>
        <el-form-item label="父级状态">
          <el-select v-model="temp.parent_id" placeholder="选择父级状态" filterable clearable>
            <el-option value="" label="无父级状态" />
            <el-option
              v-for="item in parentOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="标签颜色">
          <el-color-picker
            v-model="temp.color"
            color-format="hex"
            :predefine="predefineColors"
          />

        </el-form-item>
        <el-form-item label="处理部门" prop="currency">
          <el-select v-model="temp.crmdepartment_id" placeholder="请选择">
            <el-option
              v-for="item in crmdepartments"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="禁止编辑订单" prop="currency">
          <el-switch
            v-model="temp.forbidden_order_edit"
            active-color="#13ce66"
            inactive-color="#ff4949"
          />
          <el-tooltip class="item" effect="dark" content="该状态下是否继续支持订单核心信息编辑，否则无法进行订单的修改" placement="top-start">
            <i class="el-icon-warning" />
          </el-tooltip>
        </el-form-item>
        <el-form-item label="指定审批人">
          <el-select v-model="temp.manager_id" placeholder="审批人" filterable size="mini" clearable>
            <el-option value="" label="不需要审批" />
            <el-option
              v-for="item in projectUsers"
              :key="item.id"
              :label="item.first_name + ' ' + item.last_name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="钉钉群通知链接">
          <el-input v-model="temp.dingding_hook" />
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="innerDialogVisible = false">取 消</el-button>
        <el-button :type="action !== 'delete'?'primary':'danger'" :loading="editloading" @click="confirm">确 定</el-button>
      </span>
    </el-dialog>

    <!-- SOP设置对话框 -->
    <crm-order-state-s-o-p
      :visible.sync="sopDialogVisible"
      :state-id="currentState.id"
      :state-name="currentState.name"
      @saved="handleSOPSaved"
    />
  </div>
</template>

<script>
import { Get, Post, Put, Delete } from '@/api/crm/crmorderstate'
import { Get as GetDepartments } from '@/api/crm/crmdepartment'
import { CRMGetProjectUsers } from '@/api/crm/crmmanage'
import CrmOrderStateSOP from './elements/crmorderstatesop'
import qs from 'qs'
import Sortable from 'sortablejs'
import { relationshipOptions } from '../../api/crm/crmcommon'

const orderMapper = {
  'ascending': 0,
  'descending': 1,
  'null': ''
}
export default {
  name: 'Crmorderstate',
  components: {
    CrmOrderStateSOP
  },
  data() {
    return {
      data: [],
      projectUsers: [],
      listLoading: false,
      kwInput: '',
      order_by: '',
      order_desc: orderMapper[0],
      // pagination
      pagesize: 500,
      page: 1,
      total: 0,

      action: null,
      dialogVisible: false,
      title: '',
      temp: {
        name: '',
        dingding_hook: '',
        forbidden_order_edit: false,
        crmdepartment_id: '',
        manager_id: '',
        parent_id: '',
        operator_role: 'sales',
        color: ''
      },
      crmdepartments: [],
      relationshipOptions: relationshipOptions,
      predefineColors: [
        '#6C6762',
        '#67C23A',
        '#F56C6C',
        '#ff4500',
        '#ff8c00',
        '#ffd700',
        '#00ced1',
        '#1e90ff',
        '#c71585'
      ],
      width: '',
      innerDialogVisible: false,
      editloading: false,
      sortable: null,
      oldList: [],
      newList: [],

      // SOP相关数据
      sopDialogVisible: false,
      currentState: {}
    }
  },
  computed: {
    // 获取可以作为父级的状态选项（没有parent_id的状态）
    parentOptions() {
      return this.data.filter(item => !item.parent_id)
    }
  },
  created() {
    this.getList()
    this.handleCRMGetProjectUsers()
    this.handleGetDepartments()
  },
  methods: {
    resetTemp() {
      this.temp = {
        name: '',
        forbidden_order_edit: false,
        manager_id: '',
        crmdepartment_id: '',
        dingding_hook: '',
        parent_id: '',
        color: ''
      }
    },
    handleGetDepartments() {
      GetDepartments(null, qs.stringify({
        pagesize: 100,
        page: 1
      }))
        .then(response => {
          this.crmdepartments = response.data.data
        }).catch(err => {
          console.log(err)
        })
    },
    getList() {
      this.listLoading = true
      Get(null, qs.stringify({
        kw: this.kwInput,
        pagesize: this.pagesize,
        all: '1',
        page: this.page,
        order_by: 'index',
        order_desc: this.order_desc
      }))
        .then(response => {
          this.data = response.data.data
          this.listLoading = false
          this.total = response.data.total
          this.oldList = this.data.map(v => v.id)
          this.newList = this.oldList.slice()
          this.$nextTick(() => {
            this.setSort()
          })
        }).catch(err => {
          console.log(err)
          this.listLoading = false
        })
    },
    updateParentChildRelation() {
      // 遍历父项目
      if (this.data !== undefined && this.data.length) {
        this.data.forEach((parentItem, parentIndex) => {
        // 更新父项目的 index
          parentItem.index = parentIndex
          console.log(parentItem.name, parentIndex)
          Put(parentItem.id, { index: parentIndex }).then((response) => {
            console.log(response)
          })
        })
      }

      // 如果你需要的话，这里可以添加代码来同步更新到服务器
    },
    setSort() {
      const el = this.$refs.dragTable.$el.querySelectorAll('.el-table__body-wrapper > table > tbody')[0]
      this.sortable = Sortable.create(el, {
        ghostClass: 'sortable-ghost', // Class name for the drop placeholder,
        setData: function(dataTransfer) {
          // to avoid Firefox bug
          // Detail see : https://github.com/RubaXa/Sortable/issues/1012
          dataTransfer.setData('Text', '')
        },
        onEnd: evt => {
          const targetRow = this.data.splice(evt.oldIndex, 1)[0]
          this.data.splice(evt.newIndex, 0, targetRow)
          // for show the changes, you can delete in you code
          const tempIndex = this.newList.splice(evt.oldIndex, 1)[0]
          this.newList.splice(evt.newIndex, 0, tempIndex)
          // console.log(this.data)
          this.updateParentChildRelation()
        }
      })
    },
    handleAction(action, row) {
      this.action = action
      switch (action) {
        case 'addchildren':
          this.resetTemp()
          this.title = row.name + '新增子状态'
          this.temp.parent_id = row.id
          this.innerDialogVisible = true
          this.action = 'create'
          break
        case 'create':
          this.width = '50%'
          this.title = '新增'
          this.resetTemp()
          this.innerDialogVisible = true
          break
        case 'delete':
          this.width = '30%'
          this.title = `确认要删除${row.name}?`
          this.temp = Object.assign({}, row)
          // 确保布尔值字段是正确的类型
          this.temp.forbidden_order_edit = Boolean(this.temp.forbidden_order_edit)
          this.innerDialogVisible = true
          break
        case 'edit':
          this.width = '50%'
          this.title = `修改${row.name}`
          // 先重置temp，确保清空之前的数据
          this.resetTemp()
          // 重新赋值所有字段
          Object.keys(this.temp).forEach(key => {
            if (row.hasOwnProperty(key)) {
              // 对于布尔值字段，确保是布尔类型
              if (key === 'forbidden_order_edit') {
                this.temp[key] = Boolean(row[key])
              } else {
                this.temp[key] = row[key] || ''
              }
            }
          })
          this.temp.id = row.id
          this.innerDialogVisible = true
          break
        case 'sop':
          this.currentState = row
          this.sopDialogVisible = true
          break
      }
    },
    confirm() {
      const _data = this.temp
      // 确保 forbidden_order_edit 是布尔值
      _data.forbidden_order_edit = Boolean(_data.forbidden_order_edit)
      switch (this.action) {
        case 'create':
          this.editloading = true
          Post(_data
          ).then(response => {
            this.innerDialogVisible = false
            this.editloading = false
            this.getList()
            this.notify('添加成功')
          })
          break
        case
          'delete'
          :
          this.editloading = true
          Delete(_data.id).then((response) => {
            this.innerDialogVisible = false
            this.editloading = false
            this.getList()
            this.$emit('reload')
            this.notify('删除成功')
          })
          break
        case
          'edit'
          :
          this.editloading = true
          Put(_data.id, _data).then((response) => {
            this.innerDialogVisible = false
            this.editloading = false
            this.getList()
            this.notify('更新成功')
          })
          break
      }
    },
    handleCRMGetProjectUsers() {
      CRMGetProjectUsers(qs.stringify({
        pagesize: 100,
        page: 1,
        order_by: this.order_by,
        order_desc: this.order_desc
      }))
        .then(response => {
          this.projectUsers = response.data.data
        }).catch(err => {
          console.log(err)
        })
    },
    notify(message, duration) {
      this.$notify({
        title: '成功',
        message: message,
        type: 'success',
        duration: duration || 2000
      })
    },
    // pageSize 改变后触发 table 更新
    handleSizeChange(val) {
      this.pagesize = val
      this.getList()
    },
    // page 改变后触发 table 更新
    handlePageChange(val) {
      this.page = val
      this.getList()
    },
    // 点击搜索
    handleSearch() {
      this.page = 1
      this.getList()
    },
    handleSort(v) {
      this.order_by = v.prop
      this.order_desc = orderMapper[v.order]
      this.getList()
    },

    handleSOPSaved() {
      // SOP保存成功的回调
      // 这里可以选择是否刷新列表以显示SOP标记
      // this.getList()
    }
  }
}
</script>

<style>
.sortable-ghost{
  opacity: .8;
  color: #fff!important;
  background: #42b983!important;
}
</style>

<style scoped>
.el-tag + .el-tag {
  margin-left: 10px;
}
.top >>> .sortable-ghost{
  opacity: .8;
  color: #fff!important;
  background: #42b983!important;
}
.top >>> .el-select .el-input {
  width: 350px;
}

.top >>> .input-with-select .el-input-group__prepend {
  background-color: #fff;
}

.top {
  padding-left: 20px;
  margin-bottom: 30px;
  margin-top: 28px;
}

.input-with-select {
  width: calc(100% - 200px);
}

.add-btn {
  float: right;
  margin-right: 20px;
  width: 150px
}

.mt-pagination {
  float: right;
  margin-top: 5px;
}

.app-container >>> .el-dialog {
  margin-top: 48px !important;
  margin-bottom: 68px;
}

.mt-dialog >>> .el-transfer-panel {
  width: calc(50% - 60px);
}

.mt-form >>> .el-select {
  width: 100%;
}

.mt-form >>> .el-input__inner {
  width: 100%;
}

.mt-dialog >>> .el-dialog {
  margin-top: 60px;
  /*margin: 168px auto !important;*/
}

.mt-dialog >>> .el-dialog__body {
  padding-bottom: 100px;
}
</style>
